package net.yxsoft.service;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.bean.FnFormParams;
import net.yxsoft.cache.ToolCache;
import net.yxsoft.kit.CustomDb;
import net.yxsoft.kit.Helper;
import net.yxsoft.kit.JsoupFilter;
import net.yxsoft.kit.RSAKit;
import net.yxsoft.model.formdesigner.FnFormData;
import net.yxsoft.model.infrastructure.TsUser;
import net.yxsoft.quorum.MyERC721;
import net.yxsoft.quorum.QuorumKit;
import net.yxsoft.resource.CodeRes;
import net.yxsoft.resource.Res;
import net.yxsoft.service.common.BaseService;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Uint;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthTransaction;
import rapid.core.Authuser;
import rapid.util.DateKit;
import rapid.util.StrKit;


import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BlockService extends BaseService {

  public static final BlockService me = new BlockService();


  /**
   * @MethodName: paginatebyBok_old
   * @Description: 内部链浏览器获取链上数据列表
   * @param: paramMap
   * @param: pageNumber
   * @param: pageSize
   * @return com.jfinal.plugin.activerecord.Page<com.jfinal.plugin.activerecord.Record>
   * @throws
   * @date 2023/10/16 14:14
   * @author wj
   */
  public List<Record> paginatebyBok_old() {

    List<Record> formDataPage =Db.find("SELECT conflict_id, DATE_FORMAT(attrib_14, '%Y-%m-%d %H:%i:%s') attrib_14, attrib_17, attrib_18,count(conflict_id) txcount " +
            "FROM s_blo_trans group by attrib_17 " +
            "ORDER BY attrib_17 DESC LIMIT 5");

    return formDataPage;
  }


  /**
   * @MethodName: paginatebyBok_old
   * @Description: 内部链浏览器获取链上数据列表
   * @param: paramMap
   * @param: pageNumber
   * @param: pageSize
   * @return com.jfinal.plugin.activerecord.Page<com.jfinal.plugin.activerecord.Record>
   * @throws
   * @date 2023/10/16 14:14
   * @author wj
   */
  public Page<Record> paginatebyBok_old(FnFormParams paramMap, int pageNumber, int pageSize) {

    Page<Record> formDataPage =Db.templateByString("SELECT conflict_id, attrib_14, attrib_17, attrib_18,\n" +
            "       CASE\n" +
            "           WHEN attrib_14 > NOW() - INTERVAL 1 MINUTE THEN CONCAT(TIMESTAMPDIFF(SECOND, attrib_14, NOW()), ' 秒前')\n" +
            "           WHEN attrib_14 > NOW() - INTERVAL 1 DAY THEN CONCAT(TIMESTAMPDIFF(MINUTE, attrib_14, NOW()), ' 分钟前')\n" +
            "           WHEN attrib_14 > NOW() - INTERVAL 1 MONTH THEN CONCAT(TIMESTAMPDIFF(DAY, attrib_14, NOW()), ' 天前')\n" +
            "           WHEN attrib_14 > NOW() - INTERVAL 1 YEAR THEN CONCAT(TIMESTAMPDIFF(MONTH, attrib_14, NOW()), ' 月前')\n" +
            "           ELSE CONCAT(TIMESTAMPDIFF(YEAR, attrib_14, NOW()), ' 年前')\n" +
            "       END AS attrib_01\n" +
            "FROM s_block\n" +
            "ORDER BY attrib_17 DESC","").paginate(pageNumber, pageSize);
    // 列表页显示 富文本 的摘要信息需要过滤为纯文本，去除所有标记
    //JsoupFilter.filterModelList(Record.getList(), 120);

    return formDataPage;
  }

  /**
   * @MethodName: paginatebyBok
   * @Description: 获取跨链链上最新区块
   * @param: val
   * @param: search
   * @return java.util.List<com.jfinal.plugin.activerecord.Record>
   * @throws
   * @date 2023/10/13 13:17
   * @author wj
   */
  public List<Record> paginatebyBok(String val,String search) {

    String valsql="";
    if(StrKit.notBlank(val)){
      valsql+=" and attrib_02='"+val+"'";
    }
    if(StrKit.notBlank(search)){

      boolean isNumeric = search.matches("-?\\d+(\\.\\d+)?");
      if (isNumeric) {
        valsql+=" and (attrib_01='"+search+"' or attrib_02='"+search+"' or attrib_03='"+search+"' or attrib_04='"+search+"' or attrib_11='"+search+"' or attrib_13='"+search+"'  )";
      }else{
        valsql+=" and (attrib_01='"+search+"' or attrib_02='"+search+"' or attrib_03='"+search+"' or attrib_04='"+search+"'  or attrib_13='"+search+"'  )";
      }

    }

    List<Record> formDataPage =Db.find("SELECT conflict_id, attrib_11,attrib_10,attrib_14,count(conflict_id) txcount " +
            "FROM s_ctransaction where 1=1 " +valsql+
            " group by attrib_11  ORDER BY attrib_11 DESC LIMIT 5");

    return formDataPage;
  }
  //全部
  public List<Record> getAllBlocks(Authuser user){
  /*  String createdby="";
    if(!user.getLoginId().equals("admin")){
      TsUser use=TsUser.dao.findById(user.getId());
      if(StrKit.notBlank(use.getPrivateKey()) && StrKit.notBlank(use.getPublicKey()))
        createdby=" where attrib_20='"+use.getId()+"'";

    }*/
    // List<Record> records = Db.find("select attrib_01,attrib_14,attrib_17,attrib_18 from s_block "+createdby+" order by attrib_14 desc limit 300");
    List<Record> records = Db.find("SELECT conflict_id, attrib_01, attrib_14, attrib_17, attrib_18,\n" +
            "       CASE\n" +
            "           WHEN attrib_14 > NOW() - INTERVAL 1 MINUTE THEN CONCAT(TIMESTAMPDIFF(SECOND, attrib_14, NOW()), ' 秒前')\n" +
            "           WHEN attrib_14 > NOW() - INTERVAL 1 DAY THEN CONCAT(TIMESTAMPDIFF(MINUTE, attrib_14, NOW()), ' 分钟前')\n" +
            "           WHEN attrib_14 > NOW() - INTERVAL 1 MONTH THEN CONCAT(TIMESTAMPDIFF(DAY, attrib_14, NOW()), ' 天前')\n" +
            "           WHEN attrib_14 > NOW() - INTERVAL 1 YEAR THEN CONCAT(TIMESTAMPDIFF(MONTH, attrib_14, NOW()), ' 月前')\n" +
            "           ELSE CONCAT(TIMESTAMPDIFF(YEAR, attrib_14, NOW()), ' 年前')\n" +
            "       END AS time_diff\n" +
            "FROM s_block\n" +
            "ORDER BY attrib_17 DESC\n" +
            "LIMIT 300;");

 /*   for(Record record : records){
      record.set("attrib_01", DateKit.frontFormat(record.getStr("attrib_14")));
    }*/
    return records;
  }

  public List getMyTran(){
    List returnList =  new ArrayList();
    //1.查出所有有效主表
    List<Record> _effective_ZHU = Db.find("select attrib_01,attrib_02,attrib_03,attrib_04,attrib_05,attrib_06,attrib_07,attrib_13,\n" +
            "attrib_14,attrib_17,attrib_21,attrib_22,attrib_23 from s_blo_trans \n" +
            "where ATTRIB_06 IS NOT NULL and ATTRIB_07 IS NOT NULL and LENGTH(attrib_06)-LENGTH(replace(attrib_06,'_',''))=1 \n" +
            "and ATTRIB_07 not in(select a.ATTRIB_07 from (select ATTRIB_07,count(*) as count from s_blo_trans  where  ATTRIB_06 IS NOT NULL and ATTRIB_07 IS NOT NULL and LENGTH(attrib_06)-LENGTH(replace(attrib_06,'_',''))=1 group by ATTRIB_07 having count>1) a) order by attrib_14 desc");
    //2.查所有有重复的主表
    List<Record> _chongfu_ZHU = Db.find("select ATTRIB_06,ATTRIB_07,count(*) as count from s_blo_trans  where  ATTRIB_06 IS NOT NULL \n" +
            "and ATTRIB_07 IS NOT NULL and LENGTH(attrib_06)-LENGTH(replace(attrib_06,'_',''))=1 group by ATTRIB_06,ATTRIB_07 having count>1");
    if(_chongfu_ZHU.size()>0) {
      for (Record zhu : _chongfu_ZHU) {
        List<Record> rs = Db.find("select attrib_01,attrib_02,attrib_03,attrib_04,attrib_05,attrib_06,attrib_07,attrib_13,\n" +
                "attrib_14,attrib_17,attrib_21,attrib_22,attrib_23 from s_blo_trans \n" +
                "where ATTRIB_06 ='" + zhu.getStr("ATTRIB_06") + "' and ATTRIB_07 = '" + zhu.getStr("ATTRIB_07") + "'\n" +
                "and attrib_14 = (select MAX(attrib_14) from s_blo_trans where ATTRIB_06 ='" + zhu.getStr("ATTRIB_06") + "' and ATTRIB_07='" + zhu.getStr("ATTRIB_07") + "')");
        for (Record r : rs) {
          _effective_ZHU.add(r);
        }
      }
    }
    if(_effective_ZHU.size()>0){
      for(Record record : _effective_ZHU){
        record.set("attrib_13", DateKit.frontFormat(record.getStr("attrib_14")));
        returnList.add(record);
        String _p=record.getStr("ATTRIB_06").substring(0,5)+"\\_%";
        List<Record> recordSon = Db.find("select attrib_01,attrib_02,attrib_03,attrib_04,attrib_05,attrib_06,attrib_07,attrib_13,attrib_14,\n" +
                "attrib_17,attrib_21,attrib_22,attrib_23 from s_blo_trans where ATTRIB_06 like '"+_p+"' and ATTRIB_07 ='"+record.getStr("ATTRIB_07")+"'" +
                " order by attrib_14 desc");
        if(recordSon.size()>0){
          for(Record record2 : recordSon) {
            record2.set("attrib_13", DateKit.frontFormat(record2.getStr("attrib_14")));
            returnList.add(record2);
          }
        }
      }
    }


    return returnList;
  }


  /**
   * @MethodName: getTransaction
   * @Description: 获取最新交易信息
   * @param: val
   * @param: search
   * @return java.util.List<com.jfinal.plugin.activerecord.Record>
   * @throws
   * @date 2023/10/13 13:18
   * @author wj
   */
  public List<Record> getTransaction(String val,String search){

    String valsql="";
    if(StrKit.notBlank(val)){
      valsql+=" and attrib_02='"+val+"'";
    }
    if(StrKit.notBlank(search)){

      boolean isNumeric = search.matches("-?\\d+(\\.\\d+)?");
      if (isNumeric) {
        valsql+=" and (attrib_01='"+search+"' or attrib_02='"+search+"' or attrib_03='"+search+"' or attrib_04='"+search+"' or attrib_11='"+search+"' or attrib_13='"+search+"'  )";
      }else{
        valsql+=" and (attrib_01='"+search+"' or attrib_02='"+search+"' or attrib_03='"+search+"' or attrib_04='"+search+"'  or attrib_13='"+search+"'  )";
      }

    }


    List<Record> records = Db.find("select conflict_id,attrib_01,attrib_03,attrib_13, DATE_FORMAT(attrib_14, '%Y-%m-%d %H:%i:%s') attrib_14" +
            "      from s_ctransaction  where 1=1 " + valsql + " order by attrib_14 desc LIMIT 20");


    return records;

  }

  /**
   * @MethodName: getTransaction_old
   * @Description: 获取最新存证上链交易信息
   * @return java.util.List<com.jfinal.plugin.activerecord.Record>
   * @throws
   * @date 2023/10/19 11:48
   * @author wj
   */
  public List<Record> getTransaction_old(){

    List<Record> records = Db.find("select conflict_id,attrib_01,attrib_03,attrib_04, DATE_FORMAT(attrib_14, '%Y-%m-%d %H:%i:%s') attrib_14" +
            "      from s_blo_trans   order by attrib_14 desc LIMIT 10");


    return records;

  }

  /**
   * @MethodName: getTrans
   * @Description: 获取内部交易信息
   * @param: user
   * @param: kxzh
   * @param: cid
   * @param: pageNumber
   * @param: pageSize
   * @return com.jfinal.plugin.activerecord.Page<com.jfinal.plugin.activerecord.Record>
   * @throws
   * @date 2023/10/16 14:27
   * @author wj
   */
  public Page<Record> getTrans(Authuser user,String kxzh,String cid,int pageNumber, int pageSize){
    String sql="";
    if(StrKit.notBlank(kxzh) && !kxzh.equals("null")){
      sql= " and attrib_03 like '%"+kxzh+"%'";
    }
    if(StrKit.notBlank(kxzh) && kxzh.equals("w") &&    StrKit.notBlank(cid)){
      Page<Record> records = Db.templateByString("SELECT a.attrib_01, a.attrib_02, a.attrib_03, a.attrib_04, a.attrib_05,\n" +
              "       a.attrib_06, a.attrib_07, a.attrib_14, a.attrib_17,\n" +
              "       a.attrib_21, a.attrib_22, a.attrib_23,\n" +
              "       CASE\n" +
              "           WHEN a.attrib_13 > NOW() - INTERVAL 1 MINUTE THEN CONCAT(TIMESTAMPDIFF(SECOND, a.attrib_13, NOW()), ' 秒前')\n" +
              "           WHEN a.attrib_13 > NOW() - INTERVAL 1 DAY THEN CONCAT(TIMESTAMPDIFF(MINUTE, a.attrib_13, NOW()), ' 分钟前')\n" +
              "           WHEN a.attrib_13 > NOW() - INTERVAL 1 MONTH THEN CONCAT(TIMESTAMPDIFF(DAY, a.attrib_13, NOW()), ' 天前')\n" +
              "           WHEN a.attrib_13 > NOW() - INTERVAL 1 YEAR THEN CONCAT(TIMESTAMPDIFF(MONTH, a.attrib_13, NOW()), ' 月前')\n" +
              "           ELSE CONCAT(TIMESTAMPDIFF(YEAR, a.attrib_13, NOW()), ' 年前')\n" +
              "       END AS attrib_13\n" +
              "FROM s_blo_trans a\n" +
              "LEFT JOIN s_block a1 ON a1.conflict_id = a.row_id\n" +
              "WHERE a1.conflict_id = '"+cid+"'" +
              "ORDER BY a.attrib_17 DESC").paginate(pageNumber, pageSize);


      return records;

    }else {
      Page<Record> records = Db.templateByString("select attrib_01,attrib_02,attrib_03,attrib_04,attrib_05,attrib_06,attrib_07, CASE\n" +
              "           WHEN attrib_13 > NOW() - INTERVAL 1 MINUTE THEN CONCAT(TIMESTAMPDIFF(SECOND, attrib_13, NOW()), ' 秒前')\n" +
              "           WHEN attrib_13 > NOW() - INTERVAL 1 DAY THEN CONCAT(TIMESTAMPDIFF(MINUTE, attrib_13, NOW()), ' 分钟前')\n" +
              "           WHEN attrib_13 > NOW() - INTERVAL 1 MONTH THEN CONCAT(TIMESTAMPDIFF(DAY, attrib_13, NOW()), ' 天前')\n" +
              "           WHEN attrib_13 > NOW() - INTERVAL 1 YEAR THEN CONCAT(TIMESTAMPDIFF(MONTH, attrib_13, NOW()), ' 月前')\n" +
              "           ELSE CONCAT(TIMESTAMPDIFF(YEAR, attrib_13, NOW()), ' 年前')\n" +
              "       END AS  attrib_13,attrib_14,attrib_17,attrib_21,attrib_22,attrib_23 from s_blo_trans  where 1=1 " + sql + " order by attrib_17 ").paginate(pageNumber, pageSize);;;

      return records;
    }
  }





  public List<Record> getTransEffective(Authuser user,String kxzh,String hash){
    String sql="";
    if(StrKit.notBlank(hash)){
      sql+= " and attrib_01 like '%"+hash+"%'";
    }
    if(StrKit.notBlank(kxzh)){
      Record ur=Db.findFirst("select id from ts_user where trust_account=?",kxzh);
      if(ur!=null) {
        sql += " and created_by = '" + ur.getStr("id") + "'";
      }else{
        sql += " and created_by is null";
      }
    }


    List<Record> records = Db.find(   "select attrib_01,attrib_02,attrib_03,attrib_04,attrib_05,attrib_06,attrib_07,attrib_13,attrib_14,attrib_17,attrib_21,attrib_22,attrib_23 from (SELECT * FROM s_blo_trans ORDER BY attrib_14  DESC  LIMIT 10000) a where 1=1 "+sql+" GROUP BY created_by order by attrib_17 desc limit 300");

    for(Record record : records){

      record.set("attrib_13", DateKit.frontFormat(record.getStr("attrib_14")));
    }
    return records;
  }

  /**
   * 获取主模型交易
   * @return
   */
  public List<Record> getMasterModelTrans(String type, String rowId){

    List<Record> master = new ArrayList<>();
    List<Record> slave = new ArrayList<>();

    if(!StrKit.isBlank(rowId) && "0".equals(type)){

      slave = Db.find("select attrib_01,attrib_02,attrib_03,attrib_04,attrib_05,attrib_06,attrib_07,attrib_13,attrib_14,attrib_17,attrib_21,attrib_22,attrib_23 from s_blo_trans where attrib_15 = ? and attrib_07 = ? limit 300", type, rowId);

      return slave;
    }else{

      master = Db.find("select attrib_01,attrib_02,attrib_03,attrib_04,attrib_05,attrib_06,attrib_07,attrib_13,attrib_14,attrib_17,attrib_21,attrib_22,attrib_23 from s_blo_trans where attrib_15 = ? limit 300", type);
    }

    for(Record record : master){

      record.set("attrib_13", DateKit.frontFormat(record.getStr("attrib_14")));
      record.set("modeltrans", getMasterModelTrans("0" ,record.getStr("attrib_07")));
    }
    return master;
  }

  /**
   * 存储上链缓存数据
   */
  public void saveCache(String cid){
    FnFormData fnFormData=  ToolCache.get(Res.BLOCK_CACHE,cid);

    Record fid= Db.findFirst("select id from fn_form where code=?", Res.BLOCK_FROMCODE);
    /**
     * attrib_07 createdBy
     * attrib_08 lastUpdBy
     * attrib_10 eimSource
     * attrib_100 attrStr
     * attrib_58 callbackUrl
     * attrib_33 上链状态
     * attrib_34 回调失败次数
     * attrib_12 上链返回值
     * attrib_19 回调返回信息
     * attrib_38 业务流水ID
     * attrib_14 回调时间
     * attrib_20 publicKey
     */
    if(fid!=null) {
      CustomDb.updateWithExceptionHandling("insert into fn_form_data (conflict_id,attrib_01,attrib_07,attrib_08,attrib_10,attrib_100,attrib_58,attrib_33,attrib_20,attrib_38) values (?,?,?,?,?,?,?,?,?,?)", fnFormData.getConflictId(), fid.getStr("id"), fnFormData.getAttrib07(),fnFormData.getAttrib08(), fnFormData.getAttrib10(), fnFormData.getAttrib100(), fnFormData.getAttrib58(), "未上链", fnFormData.getAttrib20(),fnFormData.getAttrib38());
    }
  }

  public Record getTransDetail(String txHash,Authuser user) throws Exception {

    EthTransaction transaction = QuorumKit.ethTransactionByHash(txHash);
    Record record = null;
    if(null != transaction.getResult()){

      record = new Record();
      record.set("txHash",txHash);
      record.set("status","Sucess");
      record.set("block",transaction.getResult().getBlockNumber());
      record.set("timestamp",transaction.getResult().getCreates());
      record.set("from",transaction.getResult().getFrom());
      record.set("to",transaction.getResult().getTo());
      record.set("value",transaction.getResult().getValue());
      record.set("gaslimit",transaction.getResult().getGas());
      record.set("gasprice",transaction.getResult().getGasPrice());
      record.set("Nonce",transaction.getResult().getNonce());
      record.set("method","createModel");
      record.set("methodId", transaction.getResult().getInput().substring(2, 10));
      EthBlock ethBlock= QuorumKit.ethBlock(transaction.getResult().getBlockNumber().intValue());
      record.set("parenthash",ethBlock.getResult().getParentHash());

      if(transaction.getResult().getInput().startsWith("0x"+ transaction.getResult().getInput().substring(2, 10))){

        List<Type> types = QuorumKit.decode(transaction.getResult().getInput(), transaction.getResult().getInput().substring(2, 10));
        BigInteger conflictId = (BigInteger) types.get(0).getValue();
        BigInteger rowId = (BigInteger) types.get(1).getValue();
        BigInteger parRowId = (BigInteger) types.get(2).getValue();
        String created = (String) types.get(3).getValue();
        String createBy = (String) types.get(4).getValue();
        String lastUpd = (String) types.get(5).getValue();
        String lastUpdBy = (String) types.get(6).getValue();
        BigInteger modificationNum = (BigInteger) types.get(7).getValue();
        String eimSource = (String) types.get(8).getValue();
        String attribStr = (String) types.get(9).getValue();
        record.set("conflictId",conflictId);
        record.set("conflictIdRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(conflictId.longValue()))));
        record.set("rowId",rowId);
        record.set("rowIdRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(rowId.longValue()))));
        record.set("parRowId",parRowId);
        record.set("parRowIdRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(parRowId.longValue()))));
        record.set("created",created);
        record.set("createdRaw", QuorumKit.encodeString(new Utf8String(created)));
        record.set("createBy",createBy);
        record.set("createByRaw", QuorumKit.encodeString(new Utf8String(createBy)));
        record.set("lastUpd",lastUpd);
        record.set("lastUpdRaw", QuorumKit.encodeString(new Utf8String(lastUpd)));
        record.set("lastUpdBy",lastUpdBy);
        record.set("lastUpdByRaw", QuorumKit.encodeString(new Utf8String(lastUpdBy)));
        record.set("modificationNum",modificationNum);
        record.set("modificationNumRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(modificationNum.longValue()))));
        record.set("eimSource",eimSource);
        record.set("eimSourceRaw", QuorumKit.encodeString(new Utf8String(eimSource)));

        if(user!=null && !user.getLoginId().equals("admin")){
          TsUser use=TsUser.dao.findById(user.getId());
          if(StrKit.notBlank(use.getPrivateKey()) && StrKit.notBlank(use.getPublicKey()))
            record.set("attribStr",QuorumKit.getAttStr( RSAKit.pkcs8EncodedKeySpec(use.getPrivateKey(),attribStr)));
          else
            record.set("attribStr",attribStr);
        }else{
          record.set("attribStr",QuorumKit.getAttStr(attribStr));
        }

        record.set("MethodName", "createModel");
        record.set("attribStrRaw", QuorumKit.encodeString(new Utf8String(attribStr)));
        record.set("inputdata",transaction.getResult().getInput());
      }else{

        Ret ret = QuorumKit.decodeInputToTokenId(transaction.getResult().getInput());

        MyERC721 erc = QuorumKit.getERC721Contract(PropKit.get("quorum.erc721.contractAddress"), QuorumKit.privateKey);
        String tokenUrl = erc.tokenURI(BigInteger.valueOf(ret.getLong("tokenId"))).send();

        record.set("inputdata", transaction.getResult().getInput()).set("tokenUrl", tokenUrl).set("MethodName", ret.getStr("method")).set("address", ret.getStr("address")).set("tokenId",ret.getStr("tokenId"));
      }
    }
    return record;
  }

  public Record getTransDetail2(String txHash){

    EthTransaction transaction = QuorumKit.ethTransactionByHash(txHash);
    Record record = null;
    if(null != transaction.getResult()){

      record = new Record();
      record.set("txHash",txHash);
      record.set("status","Sucess");
      record.set("block",transaction.getResult().getBlockNumber());
      EthBlock ethBlock= QuorumKit.ethBlock(transaction.getResult().getBlockNumber().intValue());
      record.set("parenthash",ethBlock.getResult().getParentHash());
      record.set("timestamp",transaction.getResult().getCreates());
      record.set("from",transaction.getResult().getFrom());
      record.set("to",transaction.getResult().getTo());
      record.set("value",transaction.getResult().getValue());
      record.set("gaslimit",transaction.getResult().getGas());
      record.set("gasprice",transaction.getResult().getGasPrice());
      record.set("Nonce",transaction.getResult().getNonce());
      record.set("method","createModel");
      record.set("methodId",transaction.getResult().getInput().substring(2, 10));
      List<Type> types = QuorumKit.decode(transaction.getResult().getInput(),transaction.getResult().getInput().substring(2, 10));
      BigInteger conflictId = (BigInteger) types.get(0).getValue();
      BigInteger rowId = (BigInteger) types.get(1).getValue();
      BigInteger parRowId = (BigInteger) types.get(2).getValue();
      BigInteger created = (BigInteger) types.get(3).getValue();
      String createBy = (String) types.get(4).getValue();
      BigInteger lastUpd = (BigInteger) types.get(5).getValue();
      String lastUpdBy = (String) types.get(6).getValue();
      BigInteger modificationNum = (BigInteger) types.get(7).getValue();
      String eimSource = (String) types.get(8).getValue();
      String attribStr = (String) types.get(9).getValue();
      record.set("inputdata",transaction.getResult().getInput());
      record.set("conflictId",conflictId);
      record.set("conflictIdRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(conflictId.longValue()))));
      record.set("rowId",rowId);
      record.set("rowIdRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(rowId.longValue()))));
      record.set("parRowId",parRowId);
      record.set("parRowIdRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(parRowId.longValue()))));
      record.set("created",created);
      record.set("createdRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(created.longValue()))));
      record.set("createBy",createBy);
      record.set("createByRaw", QuorumKit.encodeString(new Utf8String(createBy)));
      record.set("lastUpd",lastUpd);
      record.set("lastUpdRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(lastUpd.longValue()))));
      record.set("lastUpdBy",lastUpdBy);
      record.set("lastUpdByRaw", QuorumKit.encodeString(new Utf8String(lastUpdBy)));
      record.set("modificationNum",modificationNum);
      record.set("modificationNumRaw", QuorumKit.encodeNumeric(new Uint(BigInteger.valueOf(modificationNum.longValue()))));
      record.set("eimSource",eimSource);
      record.set("eimSourceRaw", QuorumKit.encodeString(new Utf8String(eimSource)));


      record.set("attribStr",attribStr);


      record.set("attribStrRaw", QuorumKit.encodeString(new Utf8String(attribStr)));
    }
    return record;
  }

  public Record getTransDetail3(String txHash){
    EthTransaction transaction = QuorumKit.ethTransactionByHash(txHash);
    Record record = null;
    record = new Record();
    record.set("txHash",txHash);
    record.set("status","Sucess");
    record.set("block",transaction.getResult().getBlockNumber());
    EthBlock ethBlock= QuorumKit.ethBlock(transaction.getResult().getBlockNumber().intValue());
    record.set("parenthash",ethBlock.getResult().getParentHash());
    record.set("timestamp",transaction.getResult().getCreates());
    record.set("from",transaction.getResult().getFrom());
    record.set("to",transaction.getResult().getTo());
    record.set("value",transaction.getResult().getValue());
    record.set("gaslimit",transaction.getResult().getGas());
    record.set("gasprice",transaction.getResult().getGasPrice());
    record.set("Nonce",transaction.getResult().getNonce());
    record.set("method","createModel");
    record.set("methodId",transaction.getResult().getInput().substring(2, 10));
    return record;
  }

  //最新7天
  public List<Record> getBlocks(){
    List<Record> records = Db.find("select attrib_01,attrib_14,attrib_17,attrib_18 from s_block where attrib_14 >= (select MAX(attrib_14) from s_block)-7 order by attrib_14 desc limit 300");
    for(Record record : records){
      record.set("attrib_01", DateKit.frontFormat(record.getStr("attrib_14")));
    }
    return records;
  }






  /**
   * @MethodName: getBlockMoreinfo
   * @Description: 去获取链浏览器统计信息
   * @param: val
   * @param search
   * @return com.jfinal.plugin.activerecord.Record
   * @throws
   * @date 2023/10/13 12:47
   * @author wj
   */
  public  Record getBlockMoreinfo(String val,String search){
    Record record=new Record();
    String valsql="";
    if(StrKit.notBlank(val)){
      valsql+=" and attrib_02='"+val+"'";
    }
    if(StrKit.notBlank(search)){

      boolean isNumeric = search.matches("-?\\d+(\\.\\d+)?");
      if (isNumeric) {
        valsql+=" and (attrib_01='"+search+"' or attrib_02='"+search+"' or attrib_03='"+search+"' or attrib_04='"+search+"' or attrib_11='"+search+"' or attrib_13='"+search+"'  )";
      }else{
        valsql+=" and (attrib_01='"+search+"' or attrib_02='"+search+"' or attrib_03='"+search+"' or attrib_04='"+search+"'  or attrib_13='"+search+"'  )";
      }

    }
    Record recordblock = Db.findFirst("SELECT MAX(ATTRIB_11) as max ,COUNT(*) as num  FROM s_ctransaction where 1=1"+valsql);
    Record userinfo = Db.findFirst("SELECT COUNT(*) as num  FROM ts_user where trust_account is not null ");
    record.set("max",recordblock.get("max"));
    record.set("num",recordblock.get("num"));
    record.set("usersize",userinfo.get("num"));
    return record;

  }


  /**
   * @MethodName: getBlockMoreinfo
   * @Description: 去获取链浏览器统计信息
   * @return com.jfinal.plugin.activerecord.Record
   * @throws
   * @date 2023/10/13 12:47
   * @author wj
   */
  public  Record getBlockMoreinfo_old(){
    Record record=new Record();
    Record recordblock = Db.findFirst("SELECT MAX(ATTRIB_17) as max ,COUNT(*) as num  FROM s_blo_trans ");
    Record userinfo = Db.findFirst("SELECT COUNT(*) as num  FROM ts_user where trust_account is not null ");
    record.set("max",recordblock.get("max"));
    record.set("num",recordblock.get("num"));
    record.set("usersize",userinfo.get("num"));
    return record;

    }


/**
* @MethodName: getqklLsit
* @Description: 获取区块链消息
* @param: authuser
* @return java.util.List<com.jfinal.plugin.activerecord.Record>
* @throws
* @date 2023/10/18 22:24
* @author wj
*/
  public  List<Record> getqklLsit(Authuser authuser){

    List<Record> recordqkl = Db.find("SELECT t.* FROM s_chain t left join s_chaintouser t1 on t.attrib_01=t1.attrib_02 where t1.attrib_01=?  order by t.created",authuser.getId());

    return recordqkl;

  }




}
